package com.kintreda.ieco_server.module.account.web;

import com.kintreda.ieco_server.bean.account.Menu;
import com.kintreda.ieco_server.bean.account.Role;
import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IMenuService;
import com.kintreda.ieco_server.module.account.service.IRoleService;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.organization.service.IOrganizationService;
import com.kintreda.ieco_server.util.Assert;
import com.kintreda.ieco_server.util.DateUtil;
import com.kintreda.ieco_server.util.StringUtil;
import com.kintreda.ieco_server.util.page.PageBean;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;

/***
 * 后台用户Controller
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

	@Resource
	private IUserService userService;
	@Resource
	private IRoleService roleService;
	@Resource
	private IMenuService menuService;
	@Resource
	private IOrganizationService organizationService;

	 // 保存地址
    @Value("#{properties['upload.target']}")
    protected String target;
    
    
    // 允许格式
    @Value("#{properties['upload.allow']}")
    protected String allow;
    
    
    protected boolean isImage(String suffix) {
        return Arrays.asList(new String[]{"png", "jpg", "gif", "bmp", "jpeg"}).contains(suffix);
    }


	/******************************************************
	 * 退出登录
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginout",method=RequestMethod.GET)
	public String loginout(HttpServletRequest request) {

		try {

			HttpSession session = request.getSession(true);
			if(session != null  && !session.isNew()){
				User user = super.getUser();
				if(user != null) {
					super.setSessionAttr("User", null);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/user/login";
	}
	
	
	/****************************************************************
	 * 进入登录页面
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/login",method=RequestMethod.GET)
	public ModelAndView login() throws ParseException {
		
		ModelAndView mv = new ModelAndView("login");
		

		return mv;
	}

	@RequestMapping(value = "/login",method=RequestMethod.POST)
	@ResponseBody
	public R login(String account,String password,String imgCode) {

		String code = this.getSession().getAttribute("imgCode").toString().toUpperCase();
		imgCode = imgCode.toUpperCase();
		if(!code.equals(imgCode)) {
			return R.error("验证码不正确");
		}

		User userDB = userService.getByAccount(account);
		if(userDB == null){
			userDB = userService.queryByMobile(account);
			if (userDB==null){
				return R.error("账号不存在！");
			}

		}
		if("2".equals(userDB.getType())||"4".equals(userDB.getType())){
			return R.error("普通用户没有权限访问");
		}

		try {
			String passwordObj = new SimpleHash("MD5",password,userDB.getSalt(),1).toString();
			if(!userDB.getPassword().equals(passwordObj)){
				return R.error("账号或密码错误");
			}

			Subject subject = SecurityUtils.getSubject();//获取当前用户对象
			//生成令牌(传入用户输入的账号和密码)
			UsernamePasswordToken token = new UsernamePasswordToken(account,password);
			token.setRememberMe(false);
			//认证登录
			//这里会加载自定义的realm
			//把令牌放到login里面进行查询,如果查询账号和密码时候匹配,如果匹配就把user对象获取出来,失败就抛异常
			subject.login(token);

			super.setSessionAttr("User", userDB);
			userDB.setLastLoginTime(DateUtil.getDate(DateUtil.YYYY_MM_DD_HH_MM_SS));
			userService.update(userDB);

			return R.ok("登录成功");

		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof org.apache.shiro.authc.IncorrectCredentialsException) {
				return R.error("账号或密码错误");
			} else {
				return R.error("登录发生错误:" + e.getMessage());
			}
		}

	}

	/******************************************************
	 * 进入后台管理主页
	 * @return
	 */
	@RequestMapping(value = "/manage",method=RequestMethod.GET)
	public ModelAndView manage() {

		ModelAndView mv = new ModelAndView("manage");
		if(Assert.notNull(this.getUser())) {
			List<Menu> menus = this.menuService.getMenuByUserId(this.getUser());
			mv.addObject("menus", menus);
		}

		return mv;
	}

	@RequestMapping(value = "/query",method=RequestMethod.GET)
	public ModelAndView query(){

		if (getUser().getType().equals("3")){
			return new ModelAndView("account/user/user-list-org");
		}

		ModelAndView mv = new ModelAndView("account/user/user-list");
		List<Role> roles = roleService.getValidRoles(null);
		mv.addObject("roles", roles);
		return mv;

	}


	
	@RequestMapping(value = "/query",method=RequestMethod.POST)
	@ResponseBody
	public Object query(@RequestParam(value = "page",defaultValue="1") Integer page,
						@RequestParam(value = "rows",defaultValue="10") Integer rows,User user,String keyword){
		if ("3".equals(getUser().getType())){
			List<User> query = userService.query("from User where orgid = ?", new Object[]{getUser().getOrgId()});
			for (User u : query) {
				String orgName = organizationService.getByAndminId(u.getId()).getName();
				u.setDepName(orgName);
			}
			return query;
		}
		PageBean<User> pageObj = new PageBean<User>();
		pageObj.setPage(page);
		pageObj.setRows(rows);
		pageObj = userService.query(pageObj, user,getUser().getType());
		return pageObj;
	}

	/****************************************************************
	 * 进入添加用户的页面
	 * @return
	 */
	@RequestMapping(value = "/add",method=RequestMethod.GET)
	public ModelAndView add() {
		ModelAndView mv = new ModelAndView("account/user/user-add");
		List<Role> roles= new LinkedList<>();
		if ("3".equals(getUser().getType())){
			roles=roleService.getRoleByategory("2");
		}else {
			roles=roleService.query("from Role ",null);
		}
		mv.addObject("user",getUser());
		mv.addObject("roles", roles);
		return mv;
	}

	/****************************************************************
	 * 添加用户信息
	 * @param user
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/add",method=RequestMethod.POST)
	@ResponseBody
	@Transient
	public R add(User user,String[] roleId) {

		try {
			User userDB=new User();
			if (StringUtils.isNotBlank(user.getName())) {
				userDB = userService.getByAccount(user.getName());//验证用户名
				if(userDB != null) {
					return R.error("用户名已存在请换一个用户名");
				}
			}
				userDB = userService.getByAccount(user.getMobile());//验证手机号
				if(userDB == null) {
					return R.error("此手机号未注册,请先使用此手机号注册再添加!");
				}
			switch (user.getType()){
				case "1":userDB.setType("1");
					break;
				case "5":
					userDB.setType("5");
					default:
						break;
			}
			userDB.setUserCode("6"+ StringUtil.getLongUID());
			userDB.setStatus("1");
				if(roleId != null) {
					Set<Role> roles = new HashSet<Role>();
					for (int i = 0; i < roleId.length; i++) {
						Role role = roleService.get(roleId[i]);
						roles.add(role);
					}
					userDB.setRoles(roles);
				}
				String salt = StringUtil.getRandom(4);
				userDB.setSalt(salt);
				Object passwordObj = new SimpleHash("MD5",user.getPassword(),salt,1);
				userDB.setPassword(passwordObj.toString());
				userService.update(userDB);
				return R.ok("添加用户成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("添加用户发生错误:" + e.getMessage());
		}
	}


	/****************************************************************
	 * 进入修改页面
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}",method=RequestMethod.GET)
	public ModelAndView edit(@PathVariable("id") String id) {
		ModelAndView mv = new ModelAndView("account/user/user-edit");
		User user = userService.get(id);
		List<Role> roles= new LinkedList<>();
		if ("3".equals(getUser().getType())){
			roles=roleService.getRoleByategory("3");
		}else {
			roles=roleService.query("from Role ",null);
		}
		mv.addObject("user", user);
		mv.addObject("roles", roles);
		return mv;
	}


	/****************************************************************
	 * 修改用户信息
	 * @param user
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/edit",method=RequestMethod.POST)
	@ResponseBody
	public R edit(User user,String[] roleId) {

		try {
			User userDB = userService.get(user.getId());
			userDB.setName(user.getName());
			userDB.setMobile(user.getMobile());
			userDB.setGender(user.getGender());
			userDB.setIdcard(user.getIdcard());
			userDB.setTrueName(user.getTrueName());

			if(StringUtils.isNotBlank(user.getPassword())){
				Object passwordObj = new SimpleHash("MD5",user.getPassword(),userDB.getSalt(),1);
				userDB.setPassword(passwordObj.toString());
			}
			if (roleId != null) {
				Set<Role> roles = new HashSet<Role>();
				for (int i = 0; i < roleId.length; i++) {
					Role role =  roleService.get(roleId[i]);
					roles.add(role);
				}
				userDB.setRoles(roles);
			}

			userService.update(userDB);
			return R.ok("修改用户成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("修改用户发生错误:" + e.getMessage());
		}
	}

	@RequestMapping("/editpassword")
	public ModelAndView editpassword(String id){
		return new ModelAndView("account/user/user-edit-password").addObject("id",id);
	}

	@RequestMapping(value = "/saveeditpassword",method = RequestMethod.POST)
	@ResponseBody
	public Object saveeditpassword(String jiupassword ,String password,String id ){
		User user = userService.get(id);
		String oldpassword = new SimpleHash("MD5",jiupassword,user.getSalt(),1).toString();
		if (StringUtils.equals(oldpassword,user.getPassword())){
			String newPwd = new SimpleHash("MD5",password,user.getSalt(),1).toString();
			user.setPassword(newPwd);
			userService.update(user);
			return R.ok("修改成功!");
		}else{
			return  R.error("请输入正确原密码!");
		}
	}



	
}
